import requests
import json
from com.demo1.redis_demo.redis_client import RedisHelper

api_key = "smdbfkjsdfghjsdfkjsdsdsdkfbsdfbsd"
secret_key = "erty2345vcbnlkjhgfcv"
app_id = "123456789"


def get_access_token():
    """
    使用 API Key，Secret Key 获取access_token，替换下列示例中的应用API Key、应用Secret Key
    """
    access_token = RedisHelper().get_by_key("qian_fan_access_token")

    if access_token:
        print(f"get_access_token from redis. token：{access_token}")
        return access_token

    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}"

    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    access_token = response.json().get("access_token")
    if access_token:
        RedisHelper().set_by_key("qian_fan_access_token", access_token, 24 * 60 * 60 * 1000)
    return access_token
